<template>
  <view class="user-edit-container">
    <view class="header-section">
      <text class="page-title">{{ isEdit ? '编辑用户' : '创建用户' }}</text>
    </view>
    
    <view class="form-section">
      <view class="form-item">
        <text class="form-label">用户名</text>
        <input class="form-input" v-model="userForm.username" placeholder="请输入用户名" />
      </view>
      
      <view class="form-item">
        <text class="form-label">邮箱</text>
        <input class="form-input" v-model="userForm.email" placeholder="请输入邮箱" />
      </view>
      
      <view class="form-item">
        <text class="form-label">手机号</text>
        <input class="form-input" v-model="userForm.phone" placeholder="请输入手机号" />
      </view>
      
      <view class="form-item" v-if="!isEdit">
        <text class="form-label">密码</text>
        <input class="form-input" v-model="userForm.password" placeholder="请输入密码" password />
      </view>
      
      <view class="form-item">
        <text class="form-label">角色</text>
        <picker mode="selector" :range="roleOptions" @change="onRoleChange">
          <view class="form-input">{{ selectedRole || '请选择角色' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">状态</text>
        <view class="status-toggle">
          <switch :checked="userForm.status === 1" @change="onStatusChange" />
          <text class="status-text">{{ userForm.status === 1 ? '启用' : '禁用' }}</text>
        </view>
      </view>
    </view>
    
    <view class="action-section">
      <button class="action-button" @click="saveUser">保存</button>
      <button class="action-button cancel" @click="cancel">取消</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { userApi } from '../../../src/services/system'

// 定义用户表单类型
interface UserForm {
  id?: number
  username: string
  email: string
  phone: string
  password?: string
  role: string
  status: number
}

// 是否为编辑模式
const isEdit = ref(false)

// 用户表单数据
const userForm = ref<UserForm>({
  username: '',
  email: '',
  phone: '',
  password: '',
  role: '',
  status: 1
})

// 角色选项
const roleOptions = ['admin', 'coach', 'member']
const selectedRole = ref('')

// 页面加载时初始化
onMounted(() => {
  initPage()
})

// 初始化页面
const initPage = () => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage: any = pages[pages.length - 1]
  const options = currentPage.$route?.query || {}
  
  // 如果有id参数，则为编辑模式
  if (options.id) {
    isEdit.value = true
    userForm.value.id = parseInt(options.id)
    fetchUserDetail(userForm.value.id)
  }
}

// 获取用户详情
const fetchUserDetail = async (userId: number) => {
  try {
    const response: any = await userApi.getUserDetail(userId)
    const userData = response.data
    
    userForm.value = {
      id: userData.id,
      username: userData.username,
      email: userData.email,
      phone: userData.phone,
      role: userData.role,
      status: userData.status
    }
    
    selectedRole.value = userData.role
    
    uni.showToast({
      title: '获取用户信息成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取用户信息失败:', error)
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none'
    })
  }
}

// 角色选择变化
const onRoleChange = (e: any) => {
  selectedRole.value = roleOptions[e.detail.value]
  userForm.value.role = selectedRole.value
}

// 状态切换变化
const onStatusChange = (e: any) => {
  userForm.value.status = e.detail.value ? 1 : 0
}

// 保存用户
const saveUser = async () => {
  // 表单验证
  if (!userForm.value.username) {
    uni.showToast({
      title: '请输入用户名',
      icon: 'none'
    })
    return
  }
  
  if (!userForm.value.email) {
    uni.showToast({
      title: '请输入邮箱',
      icon: 'none'
    })
    return
  }
  
  if (!userForm.value.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  
  if (!isEdit.value && !userForm.value.password) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none'
    })
    return
  }
  
  if (!userForm.value.role) {
    uni.showToast({
      title: '请选择角色',
      icon: 'none'
    })
    return
  }
  
  try {
    if (isEdit.value && userForm.value.id) {
      // 编辑用户
      await userApi.updateUser(userForm.value.id, {
        username: userForm.value.username,
        email: userForm.value.email,
        phone: userForm.value.phone,
        role: userForm.value.role,
        status: userForm.value.status
      })
      
      uni.showToast({
        title: '更新用户成功',
        icon: 'success'
      })
    } else {
      // 创建用户
      await userApi.createUser({
        username: userForm.value.username,
        email: userForm.value.email,
        phone: userForm.value.phone,
        password: userForm.value.password,
        role: userForm.value.role,
        status: userForm.value.status
      })
      
      uni.showToast({
        title: '创建用户成功',
        icon: 'success'
      })
    }
    
    // 返回用户列表页面
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  } catch (error) {
    console.error('保存用户失败:', error)
    uni.showToast({
      title: '保存用户失败',
      icon: 'none'
    })
  }
}

// 取消操作
const cancel = () => {
  uni.navigateBack()
}
</script>

<!-- ... existing style ... -->